package com.huahua.graduateschoolspringboot.util;

import cn.hutool.core.util.CoordinateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.huahua.graduateschoolspringboot.enums.DeviceTypeEnum;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LoveHuaHua
 * @date 2023年03月12日 16:52
 * @description believe in yourself
 */
@Slf4j
public class MessageUtil {

    /**
     * 包头
     */
    public static final String HEADER = "2023FF03";
    //map
    public static final Map<String, Channel> deviceMap = new ConcurrentHashMap<>();

    public static void sendMessage(String json, DeviceTypeEnum deviceTypeEnum, Integer sendCommandType) {
        log.info("准备发送json:{}", json);
        json = json + "\0";
        Channel client = deviceMap.get(deviceTypeEnum.getDeviceBaseEnum().getRole());
        if (ObjUtil.isNull(client)) {
            log.error("设备不在线...");
            return;
        }

        //包长度  指令长度+参数长度+校验和长度
        int bodyLength = json.length() + 1 + 2;
        String bodyLengthHex = StrUtil.fillBefore(HexUtil.toHex(bodyLength), '0', 4);
        String lengthHex0 = StrUtil.sub(bodyLengthHex, 2, 4);
        String lengthHex1 = StrUtil.sub(bodyLengthHex, 0, 2);

        String sendCommandFlag = deviceTypeEnum.getPackageIdentification();
        //包指令
        String finalSendCommandType = StrUtil.fillBefore(String.valueOf(sendCommandType), '0', 2);
        String jsonHex = HexUtil.encodeHexStr(json);
        String res = HEADER + sendCommandFlag + lengthHex0 + lengthHex1 + finalSendCommandType + jsonHex + "1111";
        //header
        log.info("发送的header是 {}", HEADER);
        //包标识
        log.info("发送的包标识是 {}", sendCommandFlag);
        //包长度
        log.info("发送的包长度是 {}", lengthHex0 + lengthHex1);
        //指令
        log.info("发送的包指令是 {}", finalSendCommandType);

        log.info("发送的是 {}", res);
        //发送指令
        client.writeAndFlush(res);
    }
}